<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%@page import="java.util.ArrayList"%>
<%@ include file="loginDetails.jsp" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<HTML>
<BODY>

<%!
String personId = "";
String userId = "";
String[] fields = new String[]{"Bio", "BirthDate", "BirthPlace", "Name", "Gender", "LastKnownAddress", "DeathDate", "DeathPlace", "Children", "Events"};
int[] fieldIds = new int[]{7,8,9,10,11,12,13,14,15,16};
boolean updatePermissions(JspWriter out,HttpServletRequest request,
					HttpSession session)
{
	userId = request.getParameter("userId");
	personId = request.getParameter("personId");
	boolean success = false;
    
	if(userId == null || personId == null)
		return false;
	// Should make a database connection here and check password
	try { // Load driver class
		Class.forName("com.mysql.jdbc.Driver");
	}
	catch (java.lang.ClassNotFoundException e) {
		System.err.println("ClassNotFoundException: " +e);
	}
	Connection con = null;
	try { 
		con = DriverManager.getConnection(url+db, uid, pwd); 
		String deleteQuery = "DELETE FROM Field WHERE Person=" + personId + " AND UserId=" + userId;
		PreparedStatement deletePreparedStmt = con.prepareStatement(deleteQuery);
		deletePreparedStmt.execute();
		
	} catch (SQLException ex) { 
	    System.err.println(ex); 
	    success= false;
	} finally {
	    if (con != null ) {
	        try {
	            con.close();
	            success = true;
	        } catch (SQLException ex) {
	            System.err.println(ex);
	            success= false;
	        }
	    }
	}	
	
	ArrayList<Integer> fieldsToAdd = new ArrayList<Integer>();
	//successful delete, add new ones in
	if(success){
		int count = 0;
		for(String s : fields){
			String temp = request.getParameter(s);
			if(temp != null && temp.equalsIgnoreCase("on")){
				fieldsToAdd.add(fieldIds[count]);
			}
			count ++;
		}
	}
	
	//now loop through the list of fields to add and put in DB
	Connection conn = null;
	try { 
		conn = DriverManager.getConnection(url+db, uid, pwd); 
	
		for(int i : fieldsToAdd){
			PreparedStatement insertStatement = conn.prepareStatement("INSERT INTO Field (FieldId, Person, UserId) VALUES (?, ?, ?)");
			insertStatement.setInt(1, i);
			insertStatement.setInt(2, Integer.parseInt(personId));
			insertStatement.setInt(3, Integer.parseInt(userId));
			insertStatement.execute();
		}
	} catch (SQLException ex) { 
	    System.err.println(ex); 
	    success= false;
	} finally {
	    if (con != null ) {
	        try {
	            con.close();
	            success = true;
	        } catch (SQLException ex) {
	            System.err.println(ex);
	            success= false;
	        }
	    }
	}	
	
	return success;
} 
%>


<%
	//Check to see if we're logged in.
	if (session.getAttribute("UserId") == null) {
	    response.sendRedirect("index.jsp"); // Send them away if they're not logged in.
	}

	//Check if user is admin
	if ((Boolean)session.getAttribute("IsAdmin") == false) {
	    response.sendRedirect("Home.jsp"); // Send back to home
	}

	boolean success = false;
	session = request.getSession(true);// May create new session
	//try{
		success = updatePermissions(out,request,session);
	//}
	//catch(IOException e){ System.err.println(e); }
	
	if(!success)
		response.sendRedirect("EditUserPermission.jsp?&UserId="+userId); // Success
	else
		response.sendRedirect("EditUserPermission.jsp?&UserId="+userId); // Failed login
	// Redirect back to login page with a message
%>

</BODY>
</HTML>